# 导入需要的工具包
import requests  # 用于发送HTTP请求
import pandas as pd  # 用于数据处理
import matplotlib.pyplot as plt  # 用于数据可视化
from datetime import datetime  # 用于时间处理


# 基础语法演示部分
def basic_syntax_demo():
    # 变量和数据类型
    city = "Beijing"
    api_key = "your_api_key_here"  # 需要替换为实际的API密钥
    temperature = 25.5
    is_sunny = True
    cities = ["Beijing", "Shanghai", "Guangzhou"]

    # 条件判断
    if temperature > 30:
        print("It's hot today!")
    elif 20 <= temperature <= 30:
        print("Nice weather!")
    else:
        print("It's cold today!")

    # 循环结构
    print("\nCity list:")
    for index, city in enumerate(cities, 1):
        print(f"{index}. {city}")

    # 字典使用
    weather_info = {
        "city": city,
        "temperature": temperature,
        "humidity": 65,
        "description": "clear sky"
    }
    print("\nWeather information:", weather_info)


# 获取天气数据的函数
def get_weather(api_key, city):
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city,
        "appid": api_key,
        "units": "metric"
    }

    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()

        # 解析数据
        return {
            "city": data["name"],
            "temp": data["main"]["temp"],
            "humidity": data["main"]["humidity"],
            "description": data["weather"][0]["description"],
            "timestamp": datetime.fromtimestamp(data["dt"])
        }
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
        return None


def test():
    # 天气查询演示
    api_key = "your_api_key_here"  # 需要替换为实际的API密钥
    city = "London"
    # 获取天气数据
    weather_data = get_weather(api_key, city)
    if weather_data:
        print("\nCurrent Weather in", weather_data["city"])
        print(f"Temperature: {weather_data['temp']}°C")
        print(f"Humidity: {weather_data['humidity']}%")
        print(f"Conditions: {weather_data['description']}")
        print(f"Last updated: {weather_data['timestamp']}")
    # 使用pandas处理数据
    # 创建示例数据集
    dates = pd.date_range(start="2023-01-01", periods=5)
    temperatures = [22, 24, 19, 23, 25]
    df = pd.DataFrame({
        "Date": dates,
        "Temperature": temperatures,
        "City": city
    })
    print("\nTemperature DataFrame:")
    print(df)
    # 使用matplotlib绘制简单图表
    plt.figure(figsize=(8, 4))
    plt.plot(df["Date"], df["Temperature"], marker='o')
    plt.title(f"Temperature Trend in {city}")
    plt.xlabel("Date")
    plt.ylabel("Temperature (°C)")
    plt.grid(True)
    plt.savefig("temperature_trend.png")  # 保存图表
    plt.show()


# 主程序
if __name__ == "__main__":
    s="\u00e8\u00bf\u0099\u00e5\u00bc\u00a0"
    print(s)
    print(s.encode("utf-8"))
    print(s.encode("utf-8").decode("utf-8"))
    print(s.encode('latin-1').decode('unicode-escape'))  # 方法一
    print(s.encode('utf-8').decode('unicode-escape'))  # 方法二
    print(s.encode('unicode-escape').decode('utf-8'))  # 方法二

    # 基础语法演示
    basic_syntax_demo()

# 测试天气查询功能
    # test()